package com.anpy.bill.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.anpy.bill.model.param.DateLineCreateDTO;
import com.anpy.bill.model.param.DateLineQueryDTO;
import com.anpy.bill.model.param.DateLineUpdateDTO;
import com.anpy.bill.entity.DateLineEntity;
import com.anpy.bill.entity.DateLineImageEntity;
import com.anpy.bill.entity.PhotoEntity;
import com.anpy.bill.mapper.DateLineImageMapper;
import com.anpy.bill.mapper.DateLineMapper;
import com.anpy.bill.mapper.PhotoMapper;
import com.anpy.bill.service.DateLineService;
import com.anpy.bill.model.vo.DateLineVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 日历事件服务实现类
 */
@Service
public class DateLineServiceImpl extends ServiceImpl<DateLineMapper, DateLineEntity> implements DateLineService {

    @Autowired
    private DateLineMapper dateLineMapper;

    @Autowired
    private PhotoMapper photoMapper;

    @Autowired
    private DateLineImageMapper dateLineImageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createDateLine(DateLineCreateDTO createDTO, Integer userId) {
        // 创建日历事件
        DateLineEntity dateLineEntity = new DateLineEntity();
        BeanUtils.copyProperties(createDTO, dateLineEntity);
        dateLineEntity.setUserId(userId);
        
        Date now = new Date();
        dateLineEntity.setCreatedAt(now);
        dateLineEntity.setUpdatedAt(now);
        
        boolean saved = save(dateLineEntity);
        if (!saved) {
            return false;
        }

        // 处理图片
        if (CollUtil.isNotEmpty(createDTO.getPhotoUrls())) {
            return savePhotos(dateLineEntity.getId(), createDTO.getPhotoUrls(), userId);
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDateLine(DateLineUpdateDTO updateDTO, Integer userId) {
        // 检查事件是否存在且属于当前用户
        DateLineEntity existingEntity = getById(updateDTO.getId());
        if (existingEntity == null || !existingEntity.getUserId().equals(userId)) {
            return false;
        }

        // 更新基本信息
        DateLineEntity updateEntity = new DateLineEntity();
        BeanUtils.copyProperties(updateDTO, updateEntity);
        updateEntity.setUpdatedAt(new Date());
        
        boolean updated = updateById(updateEntity);
        if (!updated) {
            return false;
        }

        // 处理图片更新
        if (updateDTO.getPhotoUrls() != null) {
            // 删除原有图片关联
            deletePhotosByDateLineId(updateDTO.getId());
            
            // 添加新图片
            if (CollUtil.isNotEmpty(updateDTO.getPhotoUrls())) {
                return savePhotos(updateDTO.getId(), updateDTO.getPhotoUrls(), userId);
            }
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDateLine(Long id, Integer userId) {
        // 检查事件是否存在且属于当前用户
        DateLineEntity existingEntity = getById(id);
        if (existingEntity == null || !existingEntity.getUserId().equals(userId)) {
            return false;
        }

        // 删除图片关联
        deletePhotosByDateLineId(id);
        
        // 删除事件
        return removeById(id);
    }

    @Override
    public DateLineVO getDateLineDetail(Long id, Integer userId) {
        DateLineVO dateLineVO = dateLineMapper.selectDateLineDetailById(id, userId);
        if (dateLineVO != null) {
            // 处理图片URL列表
            List<String> photoUrls = getPhotoUrlsByDateLineId(id);
            dateLineVO.setPhotoUrls(photoUrls);
        }
        return dateLineVO;
    }

    @Override
    public IPage<DateLineVO> queryDateLines(DateLineQueryDTO queryDTO, Integer userId) {
        Page<DateLineVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        IPage<DateLineVO> result = dateLineMapper.selectDateLineWithDetails(
            page, userId, queryDTO.getEventTypeId(), 
            queryDTO.getStartTime(), queryDTO.getEndTime()
        );
        
        // 为每个事件设置图片URL列表
        if (CollUtil.isNotEmpty(result.getRecords())) {
            result.getRecords().forEach(vo -> {
                List<String> photoUrls = getPhotoUrlsByDateLineId(vo.getId());
                vo.setPhotoUrls(photoUrls);
            });
        }
        
        return result;
    }

    /**
     * 保存图片
     */
    private boolean savePhotos(Long dateLineId, List<String> photoUrls, Integer userId) {
        Date now = new Date();
        
        for (String photoUrl : photoUrls) {
            if (StrUtil.isBlank(photoUrl)) {
                continue;
            }
            
            // 创建图片记录
            PhotoEntity photoEntity = new PhotoEntity();
            photoEntity.setPhotoUrl(photoUrl);
            photoEntity.setPhotoName("日历事件图片");
            photoEntity.setUserId(userId);
            photoEntity.setCreateAt(now);
            photoEntity.setUpdateAt(now);
            
            boolean photoSaved = photoMapper.insert(photoEntity) > 0;
            if (!photoSaved) {
                return false;
            }
            
            // 创建关联记录
            DateLineImageEntity imageEntity = new DateLineImageEntity();
            imageEntity.setDateLineId(dateLineId.intValue());
            imageEntity.setPhotoId(photoEntity.getId().intValue());
            
            boolean imageSaved = dateLineImageMapper.insert(imageEntity) > 0;
            if (!imageSaved) {
                return false;
            }
        }
        
        return true;
    }

    /**
     * 删除日历事件的图片关联
     */
    private void deletePhotosByDateLineId(Long dateLineId) {
        LambdaQueryWrapper<DateLineImageEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DateLineImageEntity::getDateLineId, dateLineId.intValue());
        dateLineImageMapper.delete(queryWrapper);
    }

    /**
     * 获取日历事件的图片URL列表
     */
    private List<String> getPhotoUrlsByDateLineId(Long dateLineId) {
        LambdaQueryWrapper<DateLineImageEntity> imageQueryWrapper = new LambdaQueryWrapper<>();
        imageQueryWrapper.eq(DateLineImageEntity::getDateLineId, dateLineId.intValue());
        List<DateLineImageEntity> imageEntities = dateLineImageMapper.selectList(imageQueryWrapper);
        
        if (CollUtil.isEmpty(imageEntities)) {
            return new ArrayList<>();
        }
        
        List<Integer> photoIds = imageEntities.stream()
            .map(DateLineImageEntity::getPhotoId)
            .collect(Collectors.toList());
        
        LambdaQueryWrapper<PhotoEntity> photoQueryWrapper = new LambdaQueryWrapper<>();
        photoQueryWrapper.in(PhotoEntity::getId, photoIds);
        List<PhotoEntity> photoEntities = photoMapper.selectList(photoQueryWrapper);
        
        return photoEntities.stream()
            .map(PhotoEntity::getPhotoUrl)
            .collect(Collectors.toList());
    }
}
